<?php

/*
* 生成以及验证身份
*/

class TokenAuth
{

    public $client_id = null;
    public $tokens = array();
    public $access_token = null;
    public $clientKey = array();

    public function __construct($client_id, $key = null)
    {
        $this->client_id = $client_id;
        $this->clientKey = TokenAuthConfig::getClientKey();
        if (!$this->clientKey[$this->client_id]) {
            $this->clientKey[$this->client_id] = $this->client_id;
        }
        $this->access_token = $this->getToken($key);
        if (empty($_SESSION['TOKEN_AUTH_' . $client_id])) {
            $_SESSION['TOKEN_AUTH_' . $client_id] = array();
        }
        $this->tokens = $_SESSION['TOKEN_AUTH_' . $client_id];
    }

    public function isToken($token, $key = null)
    {
        if (!$this->client_id || !$this->access_token) {
            return false;
        }
        $code = GenerateEncrypt::decrypt($token, $this->clientKey[$this->client_id]);
        if (!$key) {
            $key = substr(session_id(), 6, 17);
        }
        //判断$key是否一致
        if ($key == $code && !isset($this->tokens[$token])) {
            return true;
        } else {
            return false;
        }
    }

    public function dropToken($token)
    {
        $_SESSION['TOKEN_AUTH_' . $this->client_id][$token] = true;
    }

    public function cleanup()
    {
        unset($_SESSION['TOKEN_AUTH_' . $this->client_id]);
    }

    private function getToken($key = null)
    {
        if (!$key) {
            $key = substr(session_id(), 6, 17);
        }
        $token = GenerateEncrypt::encrypt($key, $this->clientKey[$this->client_id]);
        return $token;
    }

}
